package com.arnold.www.service;

import com.arnold.www.dao.UserDao;
import com.arnold.www.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @ClassName UserServiceImpl
 * @Description: TODO
 * @Author Arnold
 * @Date 2020/4/26
 * @Version V2.0
 **/
@Service
public class UserServiceImpl implements UserService {

    @Resource
    UserDao userDao;

    //模拟服务降级处理
    @HystrixCommand(fallbackMethod = "fallback",
            commandProperties = {@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="3000")})
    @Override
    public User checkLogin(User user) {
        /*try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        return userDao.checkLogin(user);
    }

    public User fallback(User user){
        user.setName("服务降级!!!!");
        return user;
    }
    public User fallbackGetUserById(Integer id){
        User user = new User();
        user.setName("服务降级,熔断!!!!");
        return user;
    }


    @Override
    //模拟服务熔断处理
    @HystrixCommand(fallbackMethod = "fallbackGetUserById",
            commandProperties = {
                    @HystrixProperty(name="circuitBreaker.enabled",value="true"), //开启断路器
                    @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value="10"), //请求次数
                    @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value="10000"), //休眠窗口时间
                    @HystrixProperty(name="circuitBreaker.errorThresholdPercentage",value="60") //失败率达到多少触发服务熔断
            })
    public User breaker(Integer id) {
        if (id<0){
            throw new NumberFormatException("id 不能为负数!!!!");
        }
        else {
            User user = userDao.getUserById(id);
            return user;
        }
    }
}